export default class Net {
    constructor() {
        if (Net.instance) {
            return Net.instance;
        }
        Net.instance = this;
    }

    _params(obj) {
        let params = "?";
        for (const [k, v] of Object.entries(obj)) {
            params += `${k}=${v}&`;
        }
        return params.slice(0, -1);
    }

    async download(api, param="") {
        const url = api + this._params(param);
        const response = await fetch(url, { method: "GET" });
        return await response.blob();
    }

    async get(api, param="") {
        const url = api + this._params(param);
        const response = await fetch(url, { method: "GET" });
        return await response.json();
    }

    async post(api, param=null, type = "application/json") {
        let content = { method: "post" };
        if (type === "application/json") {
            content["body"] = JSON.stringify(param);
            content["headers"] = { "Content-Type": "application/json" };
        } else {
            content["body"] = param;
        }
        const response = await fetch(api, content);
        return await response.json();
    }

    async put(api, param) {
        let content = {
            method: "put",
            body: JSON.stringify(param),
            headers: { "Content-Type": "application/json" }
        };

        const response = await fetch(api, content);
        return await response.json();
    }

    async delete(api, param) {
        let content = {
            method: "delete",
            body: JSON.stringify(param),
            headers: { "Content-Type": "application/json" }
        };

        const response = await fetch(api, content);
        return await response.json();
    }
}